﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AdvancedDataGridView;
using SalienceEngineDemo.Manage_Options;
using System.IO;

namespace SalienceEngineDemo.Dialogs
{
    public partial class Options: Form
    {
        public enum OptionSections
        {
            NOTHING = -1,
            GENERAL = 0,
            DOCUMENTS = 1,
            ENTITIES = 2,
            SENTIMENT = 3,
            ALL = 4,
            DISPLAY = 5
        }

        public bool bChangesRequireRestart = false;
        public int m_nActiveTab = 0;

        private bool m_bLogStartup = false;
        private string m_sLicenseFile = String.Empty;
        private string m_sDataDir = String.Empty;
        private string m_sUserDir = String.Empty;
        private string m_sLogPath = String.Empty;
        private int m_nTextThreshold = 80;
        private int m_nTimeout = 0;
        private bool m_bFailOnLongSentences = true;
        private int m_nSummaryLength = 3;
        private string m_sQueryFile = String.Empty;
        private string m_sConceptFile = String.Empty;
        private string m_sSentimentFile = String.Empty;
        private string m_sEntityFile = String.Empty;
        private int m_nEntityThreshold = 55;
        private int m_nEntitySummary = 3;
        private int m_nMaxConceptHits = 5;
        private decimal m_dMinConceptScore = 0.45m;
        private ListofOptions AllOptionsList = new ListofOptions();
        private SalienceDemo m_pParent;

        public Options(SalienceDemo parent)
        {
            AllOptionsList.initialize();
            InitializeComponent();
            SetGridDrawingOptions();
            this.m_pParent = parent;
        }

        public Options(int nActiveTab, SalienceDemo parent)
        {
            AllOptionsList.initialize();
            InitializeComponent();
            SetGridDrawingOptions();
            m_nActiveTab = nActiveTab;
            this.m_pParent = parent;
        }

        private void SetGridDrawingOptions()
        {
            System.Drawing.Font boldFont = new System.Drawing.Font(AllOptions_TreeGridView.DefaultCellStyle.Font, System.Drawing.FontStyle.Bold);

            // ** START DRAWING THE GRID OPTIONS HERE ** //
            AdvancedDataGridView.TreeGridNode lastCategory = null;
            foreach (Manage_Options.OptionGridInfo info in this.AllOptionsList.optionsList)
            {
                if (info.isCategory)
                {
                    lastCategory = AllOptions_TreeGridView.Nodes.Add(info.option_name, null);
                    lastCategory.ImageIndex = 0;
                    lastCategory.DefaultCellStyle.Font = boldFont;
                    lastCategory.DefaultCellStyle.SelectionBackColor = AllOptions_TreeGridView.DefaultCellStyle.BackColor;
                    lastCategory.DefaultCellStyle.SelectionForeColor = AllOptions_TreeGridView.DefaultCellStyle.ForeColor;
                    lastCategory.ReadOnly = true;
                }
                else
                {
                    if (info.isBool)
                    {
                        AdvancedDataGridView.TreeGridNode option = lastCategory.Nodes.Add(info.option_name, null);
                        if (info.customDrop.Count == 0)
                        {
                            System.Windows.Forms.DataGridViewCheckBoxCell checkCell = new System.Windows.Forms.DataGridViewCheckBoxCell();
                            if (info.defaultVal != null)
                                checkCell.Value = System.Convert.ToBoolean(info.defaultVal);
                            option.Cells[1] = checkCell;
                        }
                        else
                        {
                            System.Windows.Forms.DataGridViewComboBoxCell comboCell = new System.Windows.Forms.DataGridViewComboBoxCell();
                            foreach (string item in info.customDrop)
                            {
                                comboCell.Items.Add(item);
                            }
                            comboCell.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
                            comboCell.Value = (string)info.defaultVal;
                            option.Cells[1] = comboCell;
                        }
                        option.ImageIndex = 1;
                    }
                    else
                    {
                        if (info.FileDirorNone == 0)
                        {
                            // It's a file!
                            AdvancedDataGridView.TreeGridNode option = lastCategory.Nodes.Add(info.option_name, info.defaultVal);
                            System.Windows.Forms.DataGridViewButtonCell buttonCell = new System.Windows.Forms.DataGridViewButtonCell();
                            buttonCell.Value = "...";
                            buttonCell.Tag = "It's a file button!";
                            option.Cells[2] = buttonCell;
                            option.ImageIndex = 1;
                        }
                        else if (info.FileDirorNone == 1)
                        {
                            // It's a directory!
                            AdvancedDataGridView.TreeGridNode option = lastCategory.Nodes.Add(info.option_name, info.defaultVal);
                            System.Windows.Forms.DataGridViewButtonCell buttonCell = new System.Windows.Forms.DataGridViewButtonCell();
                            buttonCell.Value = "...";
                            buttonCell.Tag = "It's a directory button!";
                            option.Cells[2] = buttonCell;
                            option.ImageIndex = 1;
                        }
                        else if (info.FileDirorNone == 2)
                        {
                            // It needs no browser!
                            AdvancedDataGridView.TreeGridNode option = lastCategory.Nodes.Add(info.option_name, info.defaultVal);
                            option.ImageIndex = 1;
                        }
                    }
                }
            }
        }

        private void LoadOptions()
        {
            this.Text += " - " + SalienceDemo.oConfig.activeSettings().settings["Name"];
            if (!String.IsNullOrEmpty(Properties.Settings.Default.LicensePath))
            {
                m_sLicenseFile = Properties.Settings.Default.LicensePath;
                txtLicenseFile.Text = m_sLicenseFile;
            }
            if (!String.IsNullOrEmpty(SalienceDemo.oConfig.activeSettings().settings["DataDirectory"]))
            {
                m_sDataDir = SalienceDemo.oConfig.activeSettings().settings["DataDirectory"];
                txtDataDirectory.Text = m_sDataDir;
            }
            string sDisplayName = this.m_pParent.cmbModeSwitch.Items[this.m_pParent.cmbModeSwitch.SelectedIndex].ToString();
            this.btnDeleteOptionProfile.Enabled = this.m_sDataDir.Contains(SalienceDemo.oConfig.sInstallRoot) && sDisplayName.Contains("Mode (") ? false : true;
            if (!String.IsNullOrEmpty(SalienceDemo.oConfig.activeSettings().settings["UserDirectory"]))
            {
                m_sUserDir = SalienceDemo.oConfig.activeSettings().settings["UserDirectory"];
                txtUserDirectory.Text = m_sUserDir;
            }
            if (!String.IsNullOrEmpty(SalienceDemo.oConfig.activeSettings().settings["LogPath"]))
            {
                m_sLogPath = SalienceDemo.oConfig.activeSettings().settings["LogPath"];
                txtLogPath.Text = m_sLogPath;
            }

            m_bLogStartup = Boolean.Parse(SalienceDemo.oConfig.activeSettings().settings["LogStartup"]);
            chkLogStartup.Checked = m_bLogStartup;

            m_nTextThreshold = Convert.ToInt32(SalienceDemo.oConfig.activeSettings().settings["TextThreshold"]);
            udThreshold.Value = m_nTextThreshold;

            m_nTimeout = Convert.ToInt32(SalienceDemo.oConfig.activeSettings().settings["TextTimeout"]);
            udTimeout.Value = m_nTimeout;

            m_bFailOnLongSentences = Boolean.Parse(SalienceDemo.oConfig.activeSettings().settings["FailLongSentences"]);
            chkLongSentences.Checked = m_bFailOnLongSentences;

            // Load document options
            m_sQueryFile = SalienceDemo.oConfig.activeSettings().settings["DefaultQueryTopicFile"];
            txtQueryTopicFile.Text = m_sQueryFile;

            m_sConceptFile = SalienceDemo.oConfig.activeSettings().settings["DefaultConceptTopicFile"];
            txtConceptTopicFile.Text = m_sConceptFile;

            m_nSummaryLength = Convert.ToInt32(SalienceDemo.oConfig.activeSettings().settings["SummaryLength"]);
            udSummaryLength.Value = m_nSummaryLength;

            //if (SalienceDemo.oConfig.activeSettings().settings["MaxConceptHits!=null)
            m_nMaxConceptHits = Convert.ToInt32(SalienceDemo.oConfig.activeSettings().settings["MaxConceptHits"]);
            udMaxConceptHits.Value = m_nMaxConceptHits;

            //if (SalienceDemo.oConfig.activeSettings().settings["MinConceptScore != null)
            m_dMinConceptScore = Convert.ToDecimal(SalienceDemo.oConfig.activeSettings().settings["MinConceptScore"]);
            udMinConceptScore.Value = m_dMinConceptScore;

            switch (m_nActiveTab)
            {
                case 1: // Document options
                    tabOptions.SelectedTab = pgDocuments;
                    break;
                case 2: // Entity options
                    tabOptions.SelectedTab = pgEntities;
                    break;
                case 3: // Sentiment options
                    tabOptions.SelectedTab = pgSentiment;
                    break;
                case 4: // All options
                    tabOptions.SelectedTab = pgAllOptions;
                    break;
                default:
                    tabOptions.SelectedTab = pgGeneral;
                    break;
            }

            // Load entity options
            m_sEntityFile = SalienceDemo.oConfig.activeSettings().settings["UserEntityList"];
            txtEntityFile.Text = m_sEntityFile;

            m_nEntityThreshold = Convert.ToInt32(SalienceDemo.oConfig.activeSettings().settings["EntityThreshold"]);
            udEntityThreshold.Value = m_nEntityThreshold;

            m_nEntitySummary = Convert.ToInt32(SalienceDemo.oConfig.activeSettings().settings["EntitySummaryLength"]);
            udEntitySummary.Value = m_nEntitySummary;

            // Load sentiment options: Sentiment HSD can be multiple files, pipe-separated
            m_sSentimentFile = SalienceDemo.oConfig.activeSettings().settings["DefaultHSDFile"];
            string[] arrSentimentFiles = m_sSentimentFile.Split(';');            
            for (int i=0; i<=arrSentimentFiles.GetUpperBound(0); i++)
                lstSentiment.Items.Add(arrSentimentFiles[i]);

            // Load display options
            udFontSize.Value = new decimal(Properties.Settings.Default.fFontSize);
        }


        private void Options_Load(object sender, EventArgs e)
        {
            // Get properties from application settings
            LoadOptions();

        }

        #region form button event handlers
        private void btnOK_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.OK;

            SalienceDemo.oConfig.activeSettings().settings["LogPath"] = txtLogPath.Text;
            SalienceDemo.oConfig.activeSettings().settings["LogStartup"] = chkLogStartup.Checked.ToString();

            //  MINI-HACK TO SYNCHRONIZE ALL THE OPTIONS OF OTHER TABS TOO
            if (tabOptions.SelectedTab.Text.Equals("Salience Options"))
            {
                tabOptions.SelectedIndex = 0;
                Tab_Transition(null, null);
            }
            else
            {
                tabOptions.SelectedIndex = 4;
                Tab_Transition(null, null);
                tabOptions.SelectedIndex = 0;
            }

            // SAVE ALL THE OPTIONS HERE
            int optionRollover = 0;
            SalienceDemo.oConfig.changedOptions.Clear();
            for (int categories = 0; categories < this.AllOptions_TreeGridView.Nodes.Count; categories++)
            {
                for (int option = 0; option < this.AllOptions_TreeGridView.Nodes[categories].Nodes.Count; option++)
                {
                    string sPropertyName = this.AllOptionsList.optionsList[optionRollover].propertyName;
                    string sUserChangedValue = this.AllOptions_TreeGridView.Nodes[categories].Nodes[option].Cells[1].Value.ToString();
                    while (String.IsNullOrEmpty(sPropertyName))
                    {
                        optionRollover++;
                        sPropertyName = this.AllOptionsList.optionsList[optionRollover].propertyName;
                    }
                    if (!(SalienceDemo.oConfig.activeSettings().settings[sPropertyName].Equals(sUserChangedValue)))
                    {
                        if (this.AllOptionsList.RestartRequiredOptions.Contains(sPropertyName))
                        {
                            bChangesRequireRestart = true;
                        }
                        SalienceDemo.oConfig.changedOptions.Add(sPropertyName, SalienceDemo.oConfig.activeSettings().settings[sPropertyName].ToString());
                        SalienceDemo.oConfig.activeSettings().settings[sPropertyName] = sUserChangedValue;
                    }
                    optionRollover++;
                }
            }

            
            SalienceDemo.oConfig.activeSettings().Save();

            Properties.Settings.Default.fFontSize = (float)this.udFontSize.Value;
            Properties.Settings.Default.Save();

            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void btnRestoreDefaults_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Only \"" + SalienceDemo.oConfig.activeSettings().settings["Name"] + "\" settings will be changed. Are you sure you want to restore to original settings for this profile?",
                "Salience Demo", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                SalienceDemo.oConfig.RestoreDefaults();
                DialogResult = System.Windows.Forms.DialogResult.OK;
                bChangesRequireRestart = true;
                this.Close();
            }
        }

        private void btnDeleteOptionProfile_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure you want to delete the \"" + SalienceDemo.oConfig.activeSettings().settings["Name"] + "\" option profile?", "Salience Demo", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                int nToDelete = Properties.Settings.Default.nMode;
                FileInfo SettingToDelete = new FileInfo(SalienceDemo.oConfig.activeSettings().settingsPath);
                SettingToDelete.Delete();
                Properties.Settings.Default.nMode--;
                Properties.Settings.Default.Save();
                this.m_pParent.cmbModeSwitch.Items.RemoveAt(nToDelete);
                this.m_pParent.cmbModeSwitch.SelectedIndex = nToDelete - 1;
                SalienceDemo.oConfig.userSettings.RemoveAt(nToDelete);
                this.Close();
            }
        }
        #endregion 

        #region Session startup button handlers
        private void btnLicenseFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlgFile = new OpenFileDialog();
            dlgFile.Title = "Select Salience 5 license file";
            dlgFile.DefaultExt = "v5";
            dlgFile.Filter = "Lexalytics license file (*.v5)|*.v5";
            dlgFile.Multiselect = false;
            if (dlgFile.ShowDialog() == DialogResult.OK)
            {
                txtLicenseFile.Text = dlgFile.FileName;
                bChangesRequireRestart = true;
            }
            m_sLicenseFile = txtLicenseFile.Text;
        }

        private void btnDataDirectory_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlgFolder = new FolderBrowserDialog();
            dlgFolder.Description = "Select Lexalytics data directory";
            dlgFolder.ShowNewFolderButton = false;
            if (dlgFolder.ShowDialog() == DialogResult.OK)
            {
                txtDataDirectory.Text = dlgFolder.SelectedPath;
                bChangesRequireRestart = true;
            }
            m_sDataDir = txtDataDirectory.Text;
        }

        private void btnUserDirectory_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlgFolder = new FolderBrowserDialog();
            dlgFolder.Description = "Select Lexalytics user data directory";
            dlgFolder.ShowNewFolderButton = false;
            if (dlgFolder.ShowDialog() == DialogResult.OK)
            {
                txtUserDirectory.Text = dlgFolder.SelectedPath;
                bChangesRequireRestart = true;
            }
            m_sUserDir = txtUserDirectory.Text;
        }

        private void btnLogPath_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlgFile = new SaveFileDialog();
            dlgFile.Title = "Select location for log startup file";
            dlgFile.DefaultExt = "v5log";
            dlgFile.Filter = "Lexalytics logfile (*.v5log)|*.v5log";
            if (dlgFile.ShowDialog() == DialogResult.OK)
            {
                txtLogPath.Text = dlgFile.FileName;
                bChangesRequireRestart = true;
            }
            m_sLogPath = txtLogPath.Text;
        }

        private void chkLogStartup_CheckedChanged(object sender, EventArgs e)
        {
            bChangesRequireRestart = true;
        }
        #endregion

        #region Document option button handlers
        private void btnBrowseQueryTopic_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlgFile = new OpenFileDialog();
            dlgFile.Title = "Select Salience 5 query topic file";
            dlgFile.DefaultExt = "dat";
            dlgFile.Filter = "Lexalytics query topic file (*.dat)|*.dat|All files (*.*)|*.*";
            dlgFile.Multiselect = false;
            if (dlgFile.ShowDialog() == DialogResult.OK)
                txtQueryTopicFile.Text = dlgFile.FileName;
        }

        private void btnBrowseConceptTopic_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlgFile = new OpenFileDialog();
            dlgFile.Title = "Select Salience 5 concept topic file";
            dlgFile.DefaultExt = "dat";
            dlgFile.Filter = "Lexalytics concept topic file (*.dat)|*.dat|All files (*.*)|*.*";
            dlgFile.Multiselect = false;
            if (dlgFile.ShowDialog() == DialogResult.OK)
                txtConceptTopicFile.Text = dlgFile.FileName;
        }

        #endregion

        #region Entity option button handlers
        private void btnBrowseEntityFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlgFile = new OpenFileDialog();
            dlgFile.Title = "Select Salience 5 entity file";
            dlgFile.DefaultExt = "dat";
            dlgFile.Filter = "Lexalytics data file (*.dat)|*.dat|All files (*.*)|*.*";
            dlgFile.Multiselect = false;
            if (dlgFile.ShowDialog() == DialogResult.OK)
                txtEntityFile.Text = dlgFile.FileName;
        }

        #endregion

        #region All options button handlers

        private void AllOptions_Browse_Click(object sender, DataGridViewCellEventArgs args)
        {
            if (((DataGridView)sender)[args.ColumnIndex, args.RowIndex].Tag != null)
            {
                if (((DataGridView)sender)[args.ColumnIndex, args.RowIndex].Tag.ToString().Equals("It's a file button!"))
                {
                    DialogResult ret = this.All_Options_Browse_File_Dialog.ShowDialog();
                    if (ret == System.Windows.Forms.DialogResult.OK)
                    {
                        ((DataGridView)sender)[args.ColumnIndex - 1, args.RowIndex].Value = this.All_Options_Browse_File_Dialog.FileName;
                    }
                }
                else if (((DataGridView)sender)[args.ColumnIndex, args.RowIndex].Tag.ToString().Equals("It's a directory button!"))
                {
                    DialogResult ret = this.All_Options_Browse_Folder_Dialog.ShowDialog();
                    if (ret == System.Windows.Forms.DialogResult.OK)
                    {
                        ((DataGridView)sender)[args.ColumnIndex - 1, args.RowIndex].Value = this.All_Options_Browse_Folder_Dialog.SelectedPath;
                    }
                }
            }
        }
        

        private void AllOptions_TreeGridView_DataError(object sender, DataGridViewDataErrorEventArgs anError)
        {
            // Just need this to get rid of Data Type Errors, please don't get rid of this dude
        }
        #endregion

        #region Transition Handlers

        private void Tab_Transition(object sender, EventArgs e)
        {
            m_nActiveTab = tabOptions.SelectedIndex;
            bool switchingtoAllOptions = tabOptions.SelectedTab.Text.Equals("Salience Options");
            for (int categories = 0; categories < this.AllOptions_TreeGridView.Nodes.Count; categories++)
            {
                for (int option = 0; option < this.AllOptions_TreeGridView.Nodes[categories].Nodes.Count; option++)
                {
                    AdvancedDataGridView.TreeGridNode optionNode = this.AllOptions_TreeGridView.Nodes[categories].Nodes[option];
                    optionNode.Cells[1].Value = optionNode.Cells[1].Value != null ? optionNode.Cells[1].Value.ToString() : "";
                    switch (optionNode.Cells[0].Value.ToString())
                    {
                        case "License File":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = txtLicenseFile.Text;
                            else
                            {
                                try
                                {   txtLicenseFile.Text = optionNode.Cells[1].Value != null ? optionNode.Cells[1].Value.ToString() : ""; }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = txtLicenseFile.Text;
                                }
                            }
                            break;
                        case "Data Directory":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = txtDataDirectory.Text;
                            else
                            {
                                try { txtDataDirectory.Text = optionNode.Cells[1].Value != null ? optionNode.Cells[1].Value.ToString() : ""; }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = txtDataDirectory.Text;
                                }
                            }
                            break;
                        case "User Directory":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = txtUserDirectory.Text;
                            else
                            {
                                try { txtUserDirectory.Text = optionNode.Cells[1].Value != null ? optionNode.Cells[1].Value.ToString() : ""; }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = txtUserDirectory.Text;
                                }
                            }
                            break;
                        case "Text Threshold":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = udThreshold.Value.ToString();
                            else
                            {
                                try { udThreshold.Value = Convert.ToDecimal(optionNode.Cells[1].Value); }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = udThreshold.Value.ToString();
                                }
                            }
                            break;
                        case "Max Execution Time":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = udTimeout.Value.ToString();
                            else
                            {
                                try { udTimeout.Value = Convert.ToDecimal(optionNode.Cells[1].Value); }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = udTimeout.Value.ToString();
                                }
                            }
                            break;
                        case "Maximum Hits":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = udMaxConceptHits.Value.ToString();
                            else
                            {
                                try { udMaxConceptHits.Value = Convert.ToDecimal(optionNode.Cells[1].Value); }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = udMaxConceptHits.Value.ToString();
                                }
                            }
                            break;
                        case "Minimum Score":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = udMinConceptScore.Value.ToString();
                            else
                            {
                                try { udMinConceptScore.Value = Convert.ToDecimal(optionNode.Cells[1].Value); }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = udMinConceptScore.Value.ToString();
                                }
                            }
                            break;
                        case "Fail on Long Sentence":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = chkLongSentences.Checked;
                            else
                            {
                                try { chkLongSentences.Checked = Convert.ToBoolean(optionNode.Cells[1].Value); }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = chkLongSentences.Checked;
                                }
                            }
                            break;
                        case "Concept Topic List":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = txtConceptTopicFile.Text;
                            else
                            {
                                try { txtConceptTopicFile.Text = optionNode.Cells[1].Value != null ? optionNode.Cells[1].Value.ToString() : ""; }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = txtConceptTopicFile.Text;
                                }
                            }
                            break;
                        case "Query Topic List":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = txtQueryTopicFile.Text;
                            else
                            {
                                try { txtQueryTopicFile.Text = optionNode.Cells[1].Value != null ? optionNode.Cells[1].Value.ToString() : ""; }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = txtQueryTopicFile.Text;
                                }
                            }
                            break;
                        case "Entity Threshold":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = udEntityThreshold.Value.ToString();
                            else
                            {
                                try { udEntityThreshold.Value = Convert.ToDecimal(optionNode.Cells[1].Value); }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = udEntityThreshold.Value.ToString();
                                }
                            }
                            break;
                        case "User Entity List":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = txtEntityFile.Text;
                            else
                            {
                                try { txtEntityFile.Text = optionNode.Cells[1].Value != null ? optionNode.Cells[1].Value.ToString() : ""; }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = txtEntityFile.Text;
                                }
                            }
                            break;
                        case "Set Sentiment Dictionary":
                            if (switchingtoAllOptions)
                            {
                                string strSentimentFiles = lstSentiment.Items[0].ToString();
                                for (int i = 1; i < lstSentiment.Items.Count; i++)
                                    strSentimentFiles += ";" + lstSentiment.Items[i].ToString();
                                optionNode.Cells[1].Value = strSentimentFiles;
                            }
                            else
                            {
                                string strSentimentFiles = String.Empty;
                                try 
                                { 
                                    lstSentiment.Items.Clear();
                                    strSentimentFiles = optionNode.Cells[1].Value.ToString();
                                    string[] arrSentimentFiles = strSentimentFiles.Split(';');
                                    for (int i = 0; i <= arrSentimentFiles.GetUpperBound(0); i++)
                                        lstSentiment.Items.Add(arrSentimentFiles[i]);

                                }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = strSentimentFiles;
                                }
                            }
                            break;
                        case "Summary Length":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = udSummaryLength.Value.ToString();
                            else
                            {
                                try { udSummaryLength.Value = Convert.ToDecimal(optionNode.Cells[1].Value); }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = udSummaryLength.Value;
                                }
                            }
                            break;
                        case "Entity Summary Length":
                            if (switchingtoAllOptions)
                                optionNode.Cells[1].Value = udEntitySummary.Value.ToString();
                            else
                            {
                                try { udEntitySummary.Value = Convert.ToDecimal(optionNode.Cells[1].Value); }
                                catch (Exception err)
                                {
                                    MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    optionNode.Cells[1].Value = udEntitySummary.Value;
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        } 

        #endregion


        #region Sentiment Analysis tab handlers        
        /// <summary>
        /// Set the states of the list management buttons based on the selected item index and the number of items in the list
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstSentiment_SelectedIndexChanged(object sender, EventArgs e)
        {
            // It's always OK to add
            btnBrowseSentimentDictionary.Enabled = true;
            // It's only ok to move up if you're not at the top
            btnMoveUp.Enabled = (lstSentiment.SelectedIndex > 0);
            // It's only ok to move down if you're not at the bottom
            btnMoveDown.Enabled = (lstSentiment.SelectedIndex < lstSentiment.Items.Count-1);
            // It's only ok to remove if there is at least one other sentiment dictionary
            btnRemove.Enabled = (lstSentiment.Items.Count > 1);

        }

        private void btnBrowseSentimentDictionary_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlgFile = new OpenFileDialog();
            dlgFile.Title = "Select Salience 5 hand-scored sentiment dictionary";
            dlgFile.DefaultExt = "hsd";
            dlgFile.Filter = "Lexalytics HSD file (*.hsd)|*.hsd|Lexalytics HSDX file (*.hsdx)|*.hsdx|All files (*.*)|*.*";
            dlgFile.Multiselect = false;
            if (dlgFile.ShowDialog() == DialogResult.OK)
                lstSentiment.Items.Add(dlgFile.FileName);

        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            lstSentiment.Items.RemoveAt(lstSentiment.SelectedIndex);
            lstSentiment.SelectedIndex = 0;
        }

        private void btnMoveUp_Click(object sender, EventArgs e)
        {
            MoveSentimentDictionaryItem(-1);
        }

        private void btnMoveDown_Click(object sender, EventArgs e)
        {
            MoveSentimentDictionaryItem(1);
        }

        private void MoveSentimentDictionaryItem(int direction)
        {
            // Checking selected item
            if (lstSentiment.SelectedItem == null || lstSentiment.SelectedIndex < 0)
                return; // No selected item - nothing to do

            // Calculate new index using move direction
            int newIndex = lstSentiment.SelectedIndex + direction;

            // Checking bounds of the range
            if (newIndex < 0 || newIndex >= lstSentiment.Items.Count)
                return; // Index out of range - nothing to do

            object selected = lstSentiment.SelectedItem;

            // Removing removable element
            lstSentiment.Items.Remove(selected);
            // Insert it in new position
            lstSentiment.Items.Insert(newIndex, selected);
            // Restore selection
            lstSentiment.SetSelected(newIndex, true);
        }

        #endregion

    }
}
